<template>
  <div class="app-container WaterQualityCalendar">
    <div style="display: flex; justify-content: space-between">
      <span class="describe">
        <!-- {{ describe }} -->
        <span class="seg">
          <span class="seg-icon"><svg-icon icon-class="seg"></svg-icon></span>
          <span style="cursor: pointer" @click="segmentClick">{{
            dmtitle
          }}</span>
        </span>
        <!-- <span>
          水质目标<span
            style="margin: 0 4px"
            :class="qualityLevelCode(targetLevelNames)"
          >
            {{ targetLevelNames }}
          </span>
        </span> -->
        <span
          >年度断面水质优良天数<span class="des-value">{{ meritDays }}</span
          >天
        </span>
        <span>
          优良率<span class="des-value">{{ meritRatio }} </span>%
        </span>
        <span>
          达标天数<span class="des-value">{{ standardDays }} </span>天
        </span>
        <span
          >达标率<span class="des-value">{{ standardRatio }}</span> %
        </span>
      </span>
      <div class="legend">
        <div class="sp" style="background: #ccffff"></div>
        <div>Ⅰ类</div>
        <div class="sp" style="background: #00ccff"></div>
        <div>Ⅱ类</div>
        <div class="sp" style="background: #00ff00"></div>
        <div>Ⅲ类</div>
        <div class="sp" style="background: #ffff00"></div>
        <div>Ⅳ类</div>
        <div class="sp" style="background: #ff9b00"></div>
        <div>Ⅴ类</div>
        <div class="sp" style="background: #ff0000"></div>
        <div>劣Ⅴ类</div>
        <div class="sp" style="background: #757f8d"></div>
        <div>无类别</div>
      </div>
    </div>
    <el-divider></el-divider>
    <div class="calendar-box" v-loading="loading">
      <Calendar
        v-for="i in 12"
        :key="i"
        :month="i"
        :year="query.beginTime"
        :response="calendarData"
        :monthdata="monthdata"
        :isCheck="isCheck"
        :dmid="dmid"
      />
    </div>
    <!-- :title="yeardata.SegmentName + '水质统计详情'" -->
    <el-drawer
      :size="700"
      :visible.sync="drawer"
      direction="rtl"
      :before-close="handleClose"
      :append-to-body="false"
      :destroy-on-close="true"
      custom-class="waterIndex-detail"
    >
      <template slot="title">
        <div>
          <span class="seg">
            <span class="seg-icon"><svg-icon icon-class="seg"></svg-icon></span>
            <span>{{ segmentName }}水质统计详情</span>
          </span>
        </div>
      </template>
      <div class="echarts-box">
        <span class="describe">
          <!-- {{ describe }} -->
          <span>
            <span>水质目标</span>
            <span :class="qualityLevelCode(targetLevelNames)">
              {{ targetLevelNames }}
            </span>
          </span>
          <span class="line"></span>
          <span>
            <span> 年度断面水质优良天数 </span>
            <span>
              <span class="des-value">{{ meritDays }}</span>
              天
            </span>
          </span>
          <span class="line"></span>
          <span>
            <span> 优良率 </span>
            <span>
              <span class="des-value">{{ meritRatio }}</span
              >%
            </span>
          </span>
          <span class="line"></span>
          <span>
            <span> 达标日 </span>
            <span>
              <span class="des-value">{{ standardDays }}</span
              >天
            </span>
          </span>
          <span class="line"></span>
          <span>
            <span> 达标率 </span>
            <span>
              <span class="des-value">{{ standardRatio }}</span>
            </span>
          </span>
        </span>
        <PieEcharts :echartData="yeardata" />
        <el-divider></el-divider>
        <BarEcharts :query="query" :yeardata="yeardata" :isCheck="isCheck" />
      </div>
    </el-drawer>
    <!-- <stationPanel :visible.sync="drawerVisible" direction="rtl" /> -->
  </div>
</template>
<script>
import { qualityLevelCode } from "@/utils/levelColor";
import { getAutoWaterCalendar } from "@/api/waterBusiness/interface.js";

export default {
  name: "WaterQualityCalendar",
  components: {
    Calendar: () => import("./Calendar"),
    // PieEcharts: () => import("./components/PieEcharts"),
    // BarEcharts: () => import("./components/BarEcharts"),
  },
  props: {
    dmid: {
      type: String,
      default: "",
    },
    dmtitle: {
      type: String,
      default: "",
    },
  },
  data() {
    return {
      isCheck: "0",
      qualityLevelCode,
      loading: false,
      drawer: false,
      drawerVisible: false,
      controlLevelList: [],
      query: {
        beginTime: this.parseTime(new Date(), "{y}"),
        segmentId: "",
        itemCode: "1",
      },
      rules: {
        beginTime: [
          {
            required: true,
            message: "监测时间不能为空",
            trigger: "change",
          },
        ],
        segmentId: [
          {
            required: true,
            message: "监测断面不能为空",
            trigger: "change",
          },
        ],
        itemCode: [
          {
            required: true,
            message: "监测项目不能为空",
            trigger: "change",
          },
        ],
      },
      itemList: [{ ID: "1", CNName: "水质类别" }],
      controlLevelCode: null,
      pickerOptions: {
        disabledDate(date) {
          return date.getTime() > new Date();
        },
      },
      describe: "",
      segmentName: "",
      targetLevelNames: "",
      meritDays: 0,
      meritRatio: 0,
      standardDays: 0,
      standardRatio: 0,
      calendarData: [],
      calendarDataOrigin: [],
      yeardata: {},
      monthdata: [],
      isover: false,
    };
  },
  computed: {
    month() {
      return new Date().getMonth() + 1;
    },
    conditionData() {
      const condition = {
        query: this.query,
      };
      return condition;
    },
  },
  mounted() {
    Promise.all([
      // this.getCommonItemSelectData(),
      this.$refs.segment?.initTree(),
    ]).then((result) => {
      this.handleQuery();
    });
  },
  methods: {
    conditionClick(conditionData) {
      Object.keys(conditionData).forEach((key) => {
        this[key] = conditionData[key];
      });
      this.$refs.segment?.setChecked();
      this.handleQuery();
    },
    check(checkedKeys) {
      this.handleQuery();
    },
    handleNodeClick() {
      this.handleQuery();
    },
    async getCommonItemSelectData() {
      const { code, data } = await commonItemSelectData({ isdisplayed: "1" });
      if (code === 200) {
        this.itemList = [...[{ ID: "1", CNName: "水质类别" }], ...data];
      }
    },
    handleQuery() {
      let query = {
        id: this.dmid,
        year: "2025",
      };

      getAutoWaterCalendar(query).then((result) => {
        console.log(">>>自动站的日历啊", result);
        let res = result.data;
        this.describe = "自己拼接的数据啊"; // 原有字段
        this.segmentName = "断面的名称"; // 断面名称
        this.targetLevelNames = "水质目标"; // 水质目标
        this.meritDays = result.data.dataDays; // 优良天数
        this.meritRatio = result.data.noOverStandardPropor; // 优良率
        this.standardDays = res.noOverStandardDays; // 达标天数
        this.standardRatio = res.noOverStandardPropor; // 达标率
        this.calendarDataOrigin = this.allDayLists(res.monthData) || []; // 原始日历数据
        this.calendarData = this.isover
          ? this.calendarDataOrigin.filter((item) => item.isOver === "1")
          : this.calendarDataOrigin;
        this.monthdata = this.dataWithoutDayList(res.monthData) || []; // 月度数据
        this.yeardata = result; // 年度数据
      });
      // require引用时，放src和放statci都可以，建议放static
      const result = require("./rl.json");
      console.log(">>>result", result);

      // debugger;
      // this.describe = result.yardescribe; // 原有字段
      // this.segmentName = result.segmentName; // 断面名称
      // this.targetLevelNames = result.targetLevelNames; // 水质目标
      // this.meritDays = result.meritDays; // 优良天数
      // this.meritRatio = result.meritRatio; // 优良率
      // this.standardDays = result.standardDays; // 达标天数
      // this.standardRatio = result.standardRatio; // 达标率
      // this.calendarDataOrigin = result.mapQualityLevel || []; // 原始日历数据
      // this.calendarData = this.isover
      //   ? this.calendarDataOrigin.filter((item) => item.isOver === "1")
      //   : this.calendarDataOrigin;
      // this.monthdata = result.moondescribe || []; // 月度数据
      // this.yeardata = result.yeardata || {}; // 年度数据
      return false;
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          this.loading = true;
          try {
            // 发起请求（保持原有逻辑）
            const result =
              this.isCheck === "0"
                ? await autosegmentcalendar(this.query)
                : await autosegmentcalendarAduit(this.query);

            this.describe = result.yardescribe; // 原有字段
            this.segmentName = result.segmentName; // 断面名称
            this.targetLevelNames = result.targetLevelNames; // 水质目标
            this.meritDays = result.meritDays; // 优良天数
            this.meritRatio = result.meritRatio; // 优良率
            this.standardDays = result.standardDays; // 达标天数
            this.standardRatio = result.standardRatio; // 达标率
            this.calendarDataOrigin = result.mapQualityLevel || []; // 原始日历数据
            this.calendarData = this.isover
              ? this.calendarDataOrigin.filter((item) => item.isOver === "1")
              : this.calendarDataOrigin;
            this.monthdata = result.moondescribe || []; // 月度数据
            this.yeardata = result.yeardata || {}; // 年度数据
          } catch (error) {
            if (axios.isCancel(error)) {
              console.log("请求被取消（用户操作或组件卸载）");
            } else {
              this.$message.error(
                error.response?.data?.message || error.message || "数据加载失败"
              );
            }
          } finally {
            this.loading = false;
          }
        }
      });
    },
    // 1. 提取所有 dayList 组成新数组（二维数组，每个元素是当月的 dayList）
    allDayLists(datas) {
      // return datas.map((item) => item.dayList);

      // 若需将所有日期对象「扁平化」为一维数组（如所有日期混在一起），加 .flat()：
      return datas.map((item) => item.dayList).flat();
    },

    // 2. 去除 dayList 后的剩余数据数组
    dataWithoutDayList(datas) {
      return datas.map((item) => {
        // 解构 item，排除 dayList，剩余字段组成新对象
        const { dayList, ...rest } = item;
        return rest; // 返回不含 dayList 的新对象
      });
    },
    handleClose(done) {
      done();
    },
    overChagne(value) {
      if (value) {
        this.calendarData = this.calendarDataOrigin.filter(
          (item) => item.isOver === "1"
        );
      } else {
        this.calendarData = this.calendarDataOrigin;
      }
    },
    segmentClick() {
      this.drawerVisible = true;
      this.$store.commit("SET_STATIONDATA", {
        siteType: "IsAuto",
        id: this.query.segmentId,
      }); // 断面值
    },
  },
};
</script>
<style scoped lang="scss">
// @import "~@/views/oneMap/css/leftPanel.scss"; // 左侧面板样式
@import "~@/style/variables.scss";
[data-theme="theme-dark"] {
  .WaterQualityCalendar {
    .describe {
      color: #ccc;
      .seg {
        color: #ccc;
        background-color: rgba(#fff, 0.1);
      }
    }
    .legend {
      color: #ccc;
    }
  }
  .el-drawer.waterIndex-detail {
    .seg {
      color: #ccc;
      background-color: rgba(#fff, 0.1);
    }
    .describe {
      color: #ccc;
      > span:not(.line) {
        .des-value {
          color: #ccc;
        }
      }
      .line {
        background-color: #eee;
      }
    }
  }
}
.WaterQualityCalendar {
  display: flex;
  flex-direction: column;
  overflow: hidden;
  .describe {
    display: flex;
    gap: 12px;
    align-items: baseline;
    font-size: 16px;
    .seg {
      height: 100%;
      line-height: 36px;
      padding-right: 12px;
      border-radius: 16px 0;
      display: flex;
      gap: 12px;
      align-items: center;
      font-family: Source Han Sans CN;
      color: var(--current-color);
      background-color: rgba(#409eff, 0.1);
      .seg-icon {
        width: 40px;
        text-align: center;
        border-radius: 16px 0;
        color: #ffffff;
        background-color: var(--current-color);
      }
    }
    .des-value {
      font-family: Barlow Condensed SemiBold;
      font-size: 24px;
      margin: 0 4px;
      font-style: italic;
    }
  }
  .calendar-box {
    display: grid;
    grid-template-columns: repeat(6, 1fr);
    grid-gap: 12px;
    height: 100%;
    overflow: auto;
  }
  .legend {
    display: flex;
    align-items: center;
  }
  .sp {
    width: 20px;
    height: 20px;
    margin: 0 10px;
  }
}
::v-deep {
  .el-drawer.waterIndex-detail {
    top: 70px;
    height: calc(100% - 70px);
    .echarts-box {
      height: 100%;
      display: flex;
      flex-direction: column;
      gap: 12px;
    }
    .seg {
      height: 36px;
      line-height: 36px;
      padding-right: 12px;
      border-radius: 16px 0;
      display: inline-flex;
      gap: 12px;
      align-items: center;
      font-family: Source Han Sans CN;
      color: var(--current-color);
      background-color: rgba(#409eff, 0.1);
      .seg-icon {
        color: #ffffff;
        background-color: #409eff;
        width: 40px;
        text-align: center;
        border-radius: 16px 0;
      }
    }
    .describe {
      display: flex;
      justify-content: space-around;
      font-family: Source Han Sans CN;
      font-weight: 400;
      font-size: 16px;
      color: #000000;
      line-height: 44px;
      > span:not(.line) {
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        .des-value {
          font-family: Barlow Condensed SemiBold;
          font-size: 24px;
          color: #333333;
        }
      }
      .line {
        width: 1px;
        background-color: #ececec;
        align-self: normal;
      }
    }
  }
  .el-drawer__header {
    margin-bottom: 12px;
  }
}
</style>
